const app = getApp();
const util = require('../../../../../utils/util.js');
const tools = require('../../../../../utils/tools.js');
const api = require('../../../../../utils/api.js');
const recorder = app.globalData.recorder; //引入录音对象
const innerAudioContext = app.globalData.innerAudioContext; //引入音频播放器

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		wordList: null, //单词本
		current: 0,  //当前单词在数组中的下标
		shake: false, //抖动
		rotate: false,  //旋转
        word: null, //单词数据
        recordFilePath: null,//临时录音文件地址
		isRecord: false,//是否正在录音
        isRecordPlaying: false,//是否正在播放用户录音
        isButtonClick: false,//是否有按钮被点击
        isRecordClick: false,//是否录音按钮被点击
        recordEnd: false,//录音完成

        timeToplimit: 5,//录音时间上限
        timeLowerlimit: 1,//录音时间下限
        remainingTime: 5,//录音剩余时间
        timeKeeping: 0,//录音计时时间
        voiceDuration: 0,//录音时长
        remain: 0,//播放录音剩余时间
        playtimeKeeping: 0,//播放录音计时
        playRecordText: "00:00",//播放录音时长时间格式化
        timeKeepingText: "00:00",//录音计时时长时间格式化

        score: null, //录音得分
        record_scale: 100, //分制

        isDetail: true, //是否在详情页
	},

	onLoad(options) {
        let _self = this;
        console.log('详情页一维数组',app.globalData.wordDetailList)
        let current = _self.data.current;
        // 判断单词在服务器是否已经有过发音
        if(app.globalData.wordDetailList[current].Score!=0&&app.globalData.wordDetailList[current].User_Voice_File!=''){
            _self.setData({
                wordList: app.globalData.wordDetailList,
                word: app.globalData.wordDetailList[current],
                score: app.globalData.wordDetailList[current].Score,
                recordFilePath: app.globalData.apiUrl + app.globalData.wordDetailList[current].User_Voice_File,
                recordEnd: true

            })
        }else{
            _self.setData({
                wordList: app.globalData.wordDetailList,
                word: app.globalData.wordDetailList[current],
                score: null,
                recordEnd: false

            })
        }
        // 开始监听加速度计
        // wx.startAccelerometer()
	},
    onReady() {
        let _self = this;
        //音频播放器状态
        innerAudioContext.onPlay((res) => {

            console.log('开始播放', res)
        })
        innerAudioContext.onStop((res) => {

            console.log('停止播放', res)
        })
        innerAudioContext.onEnded((res) => {

            console.log('停止播放', res)
        })
        innerAudioContext.onError((res) => {
            console.log('播放错误', res)
        })
        // 监听加速度计
        // wx.onAccelerometerChange(function(res) {
        //     if(_self.data.isDetail){
        //         if(res.x>2||res.y>2||res.z>2){
        //             console.log("触发摇一摇")
        //             _self.remember();
        //             wx.vibrateLong()
        //         }
        //     }
			
		// })
    },
    onUnload() {
        // 停止监听加速度计
        // wx.stopAccelerometer();
        // this.setData({
        //     isDetail: false
        // })
    },

	// 开始录音
    recordStart() {
        innerAudioContext.stop();
        let _self = this;
        if (_self.data.isRecordClick) {
            console.log("录音按钮被点击，请稍后再点")
            return
        }
        //录音提交参数
        let scoreCfg = {
            coreType: 'sent.eval', //测评类型 
            refText: _self.data.wordList[_self.data.current].Words, //参考文本 
            scale: 100, //分制 
            precision: 1, //精度 
            dict_type: 'kk', //音素字典选项  
            slack: 0 //宽松度 
        }
        app.aldstat.sendEvent('单词本-点击录音');
        wx.showLoading({
            title: '准备录音中'
        })
        recorder.start({
            duration: 5 * 1000, //录音时长  
            serverParams: scoreCfg, //录音传参
            //开始录音成功回调
            onStart() {
				wx.hideLoading()
				console.log("录音开始onStart");
				_self.setData({
					isRecord: true,
					isRecordClick: true,
					isRecordPlaying: false,
					timeKeeping: 0
				});
				clearInterval(_self.timer);
				let timer = setInterval(function () {
					_self.setData({
						timeKeeping: _self.data.timeKeeping + 1,
						timeKeepingText: tools.timeFormat(_self.data.timeKeeping + 1)
					});
					console.log('计时', _self.data.timeKeeping);
					// 当超出时间上限时，停止录音
					if (_self.data.timeKeeping == 5) {
						clearInterval(_self.timer);
						_self.setData({
							isRecord: false,
							isRecordClick: false,
							recordEnd: true
						})
					}
				}, 1000);
				_self.timer = timer;
            },
            //录音完成回调
            onStop(ret) {
                clearInterval(_self.timer);
                console.log('录音完成onStop', ret);
                console.log('录音时间', _self.data.timeKeeping);
                innerAudioContext.src = ret.tempFilePath;
                _self.setData({
                    recordFilePath: ret.tempFilePath,
                })
                recorder.stop();
                //   _self.voiceDuration();
                //录音完成提示震动
                wx.vibrateShort({
                    complete(res) {
                        console.log('录音完成打开震动', res)
                    }
                });
                wx.showLoading({
                    title: '录音处理中'
                })
            },
            //获取评分结果回调
            onScore(ret) {
                wx.hideLoading();
                console.log("录音评分结果onScore", JSON.parse(ret));
                let result = JSON.parse(ret).result;
                if (result) {
                    console.log('得分结果', result);
                    _self.setData({
                        score: result.overall, //录音得分
                        isRecord: false,
                        timeKeeping: 0,
                        timeKeepingText: "00:00",
                        voiceDuration: _self.data.timeKeeping,
                        isRecordClick: false,
                        recordEnd: true,
                    })
                    // 上传录音到服务器
                    _self.sumbitWordVoice()

                } else { //获取得分失败重录
                    wx.hideLoading();
                    wx.showModal({
                        title: '温馨提示',
                        content: 'Ai老师计算失误',
                        showCancel: false,
                        confirmText: '再录一次',
                        success: (res) => {
                            if (res.confirm) {
                                console.log('用户点击确定');
                                wx.hideLoading();
                                _self.setData({
                                    isRecord: false,
                                    timeKeeping: 0,
                                    timeKeepingText: "00:00",
                                    isRecordClick: false,
                                })
                            } else if (res.cancel) {
                                console.log('用户点击取消')
                            }
                        }
                    })
                }
            },
            //过程发生错误回调，目前有如下情况会触发：1、录音异常中止 2、远程服务器连接异常中止
            onError(ret) {
                wx.hideLoading();
                console.log("录音过程发生错误回调onError", ret);
                recorder.stop();
                switch (ret.errCode) {
                    case 30001:
                        //还未完成录音服务器就返回报错信息
                        _self.onErrorToRecord();
                        break;
                    case 30002:
                        //正在录音时服务器与客户端主动断开，评分服务器出错
                        _self.onErrorToRecord();
                        break;
                    case 30003:
                        //客户端网络中断或者其他异常导致客户端主动与服务器断开连接
                        _self.onErrorToRecord();
                        break;
                    case 30004:
                        //本地录音机出错，执行错误的停止开始录音流程
                        _self.onErrorToRecord();
                        break;
                    default:
                        console.log('error', ret.errMsg)
                }
            },
            fail(ret) {
                console.log("录音接口调用失败fail", ret);
                wx.hideLoading();
                wx.showModal({
                    title: '温馨提示',
                    content: '录音出了小差错，请重新录制',
                    showCancel: false,
                    success: (res) => {
                        if (res.confirm) {
                            console.log('用户点击确定')
                            _self.setData({
                                isRecord: false,
                                isPlaying: false,
                                isRecordPlaying: false,
                                isButtonClick: false,
                                isRecordClick: false,
                                recordEnd: false,
                                timeKeeping: 0,
                                timeKeepingText: "00:00",
                            })
                        }
                    }
                })
                recorder.stop();
            },
        })

	},
	// 完成录音
    recordEnd() {
        console.log("结束录音");
        let _self = this;
        //录音时间过短
        // if (_self.data.timeKeeping < 1) {
        //     console.log("点击间隔过短")
        //     return
        // }
        recorder.stop({
            success: (ret) => {
                console.log("skegn_stop success", ret)
            },
            fail: (ret) => {
                console.log("skegn_stop fail", ret)
            },
            complete: (ret) => {
                console.log("skegn_stop complete", ret)
            }
        })
        _self.setData({
            isRecord: false,
            isRecordClick: false,
        })
    },
    // 录音出错后执行的重录代码
    onErrorToRecord() {
        let _self = this;
        wx.showModal({
            title: '温馨提示',
            content: '录音出了点小差错,请重新录制',
            showCancel: false,
            confirmText: '确定',
            success: (res) => {
                _self.setData({
                    isRecord: false,
                    isRecordClick: false
                })
            },
        })
    },

    // 上传录音
    sumbitWordVoice() {
        let _self = this;
        let obj = {
            Score: _self.data.score,
            UpfileName: _self.data.recordFilePath
        }
        var voiceJson = JSON.stringify(obj); //json转字符串
        let formDic = {
            action: 'WechatSumbitWordVoice',
            AppKey: app.globalData.appkey,
            WID: _self.data.wordList[_self.data.current].Id,
            OpenId: app.globalData.openId,
            VoiceJson: voiceJson
        };
        console.log('上传数据', formDic)
        const uploadTask = wx.uploadFile({
            url: app.globalData.apiUrl + app.globalData.baseAshx,
            filePath: _self.data.recordFilePath, //that.data.recordFilePath
            name: _self.data.recordFilePath, //that.data.recordFilePath
            header: {
                'content-type': 'multipart/form-data'
            },
            formData: formDic,
            success: function (res) {
                console.log("上传成功返回的数据", res)
            },
            fail: function (err) {
                console.log("上传失败返回的数据", err)
            },
            complete: function (res) {
                wx.hideLoading();
                //上传录音完成后执行回调
                typeof callback == 'function' && callback(res);
            }
        })
    },


	// 播放用户录音
    playRecord() {
        console.log("播放用户录音")
        let _self = this;
        if (_self.data.isButtonClick) {
            console.log("已经有按钮被点击，请稍后再点")
            return
        }
        
        _self.setData({
            isRecordPlaying: true,
            isButtonClick: true,
        })
        //1s后释放状态
        setTimeout(function () {
            _self.setData({
                isButtonClick: false
            })
        }, 1000);
        innerAudioContext.src = _self.data.recordFilePath;
        innerAudioContext.play();

        innerAudioContext.onEnded((res) => {
            console.log('正常停止播放', res)
            _self.setData({
                isRecordPlaying: false,
            })
        })
    },
	// 停止播放用户录音
    stopRecord() {
        console.log("停止用户录音")
        let _self = this;
        clearInterval(_self.timer_play);
        if (_self.data.isButtonClick) {
            console.log("已经有按钮被点击，请稍后再点")
            return
        }
        innerAudioContext.stop();
        _self.setData({
            isRecordPlaying: false,
            isButtonClick: false,
        })
    },
    // 播放单词发音
    playWord(e) {
		innerAudioContext.stop();
		let src = e.currentTarget.dataset.audio;
		innerAudioContext.src = src;
		innerAudioContext.play();
		console.log("播放发音地址",src)
	},

    // 已经记住
	remember() {
        let _self = this;
		_self.setData({
			shake: true,
		})
		let wordList = _self.data.wordList;
        let current = _self.data.current;
        let dataDic = {
            OpenId: app.globalData.openId,
            WID: wordList[current].Id
        }
		wordList.splice(current, 1);
		wx.showToast({
			title: '已经删除',
			icon: 'success',
			duration: 500
        })
        app.aldstat.sendEvent('单词本-点击记住了');
		setTimeout(function (param) {
			// 判断单词在服务器是否已经有过发音
            if(_self.data.wordList[current].Score!=0&&_self.data.wordList[current].User_Voice_File!=''){
                _self.setData({
                    current: current,
                    word: _self.data.wordList[current],
                    score: _self.data.wordList[current].Score,
                    recordFilePath: app.globalData.apiUrl + _self.data.wordList[current].User_Voice_File,
                    recordEnd: true,
                    shake: false,

                })
            }else{
                _self.setData({
                    current: current,
                    word: _self.data.wordList[current],
                    score: null,
                    recordEnd: false,
                    shake: false,

                })
            }
        }, 1000)
        
        api.methodRemoveToWordBook({
            dataDic,
            success: (res) => {
                console.log('移出单词本成功',res)
			
            },
            fail: (res) => {
                console.log("移出单词本失败", res);
            },
            complete: (res) => {
                console.log(res.data);
            },
        })
    },
    // 还需练习
	needpractice() {
        let _self = this;
        let wordList = _self.data.wordList;
        let current = _self.data.current;
        let word = wordList.splice(current, 1);
        wordList.push(word[0])

		_self.setData({
			rotate: !_self.data.rotate,
        })
        app.aldstat.sendEvent('单词本-点击还需练习');
		setTimeout(function (param) {  
            // 判断单词在服务器是否已经有过发音
            if(_self.data.wordList[current].Score!=0&&_self.data.wordList[current].User_Voice_File!=''){
                _self.setData({
                    current: current,
                    word: _self.data.wordList[current],
                    score: _self.data.wordList[current].Score,
                    recordFilePath: app.globalData.apiUrl + _self.data.wordList[current].User_Voice_File,
                    recordEnd: true

                })
            }else{
                _self.setData({
                    current: current,
                    word: _self.data.wordList[current],
                    score: null,
                    recordEnd: false

                })
            }
		},500)
		
	}
})